/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Wangyunlai on 2022/6/5.
//

#pragma once

#include <vector>
#include <string.h>

#include "rc.h"
#include "sql/stmt/stmt.h"
#include "storage/common/field.h"
#include "util/comparator.h"
#include "storage/record/record.h"
#include "util/util.h"
#include "sql/expr/tuple.h"

class FieldMeta;
class FilterStmt;
class Db;
class Table;
class Aggregate;

class SelectStmt : public Stmt
{
public:

  SelectStmt() = default;
  ~SelectStmt() override;

  StmtType type() const override { return StmtType::SELECT; }
public:
  static RC create(Db *db, const Selects &select_sql, Stmt *&stmt);

public:
  const std::vector<Table *> &tables() const { return tables_; }
  const std::vector<Field> &query_fields() const { return query_fields_; }
  FilterStmt *filter_stmt() const { return filter_stmt_; }
  std::vector<Aggregate*> &aggregates() { return aggregates_; }
private:
  std::vector<Field> query_fields_;
  std::vector<Table *> tables_;
  FilterStmt *filter_stmt_ = nullptr;
  std::vector<Aggregate*> aggregates_;
};

class Aggregate
{
public:
  Aggregate(AggrType aggr_type, const char *attr_name, Field field) 
    : aggr_type_(aggr_type), attr_name_(attr_name), field_(field), flag_(false), sum_(0), count_(0) {}

  void do_record(const RowTuple *tuple) {
    switch (aggr_type_) {
      case MAX:
      case MIN: {
        TupleCell tuple_cell;
        tuple->find_cell(field_, tuple_cell);
        if (!flag_) {
          flag_ = true;
          value_ = tuple_cell;
          return;
        }

        int res = value_.compare(tuple_cell);

        if (MAX == aggr_type_) {
          if (res <= 0) {
            value_ = tuple_cell;
          }
        } else {
          if (res >= 0) {
            value_ = tuple_cell;
          }
        }
      } break;
      case COUNT: {
        count_++;
      } break;
      case AVG:
      case SUM: {
        TupleCell tuple_cell;
        tuple->find_cell(field_, tuple_cell);
        sum_ += tuple_cell.to_float();
        if (AVG == aggr_type_) {
          count_++;
        }
      } break;
      default:
        LOG_ERROR("Unknown aggregate type");
        break;
    }
  }

  std::string to_string() {
    std::string prefix;
    switch (aggr_type_) {
      case MAX: {
        prefix = "MAX(";
      } break;
      case MIN: {
        prefix = "MIN(";
      } break;
      case COUNT: {
        prefix = "COUNT(";
      } break;
      case AVG: {
        prefix = "AVG(";
      } break;
      case SUM: {
        prefix = "SUM(";
      } break;
      default:
        LOG_ERROR("Unknown aggregate type");
        break;
    }
    return prefix + std::string(attr_name_) + ')';
  }

  void value_to_string(std::ostream &os) {
    switch (aggr_type_) {
      case MAX:
      case MIN: {
        if (flag_) {
          value_.to_string(os);
        }
      } break;
      case COUNT: {
        os << std::to_string(count_);
      } break;
      case AVG: {
       auto attr_type = field_.attr_type();
        switch (attr_type) {
          case INTS:
          case FLOATS:
          case CHARS: {
            os << double2string(sum_ / (float)count_); 
          } break;
          case DATES: {
              int val = (int)(sum_ / (float)count_);
              char buf[16] = {0};
              snprintf(buf, sizeof(buf), "%04d-%02d-%02d", val/10000, (val%10000)/100, val%100);
              os << buf;
            } break;
          default: {
            LOG_WARN("unsupported attr type: %d", attr_type);
          } break;
        }
      } break;
      case SUM: {
        os << double2string(sum_);
      } break;
      default:
        LOG_ERROR("Unknown aggregate type");
        break;
    }
  }

  TupleCell to_tuplecell() {
    switch (aggr_type_) {
      case MAX:
      case MIN: {
        if (flag_) {
          return value_;
        }
      } break;
      case COUNT: {
        char *c = strdup(std::to_string(count_).c_str());
        return TupleCell(field_.attr_type(), c);
      } break;
      case AVG: {
       auto attr_type = field_.attr_type();
        switch (attr_type) {
          case INTS:
          case FLOATS:
          case CHARS: {
            char *c = strdup(double2string(sum_ / (float)count_).c_str());
            return TupleCell(field_.attr_type(), c);
          } break;
          case DATES: {
              int val = (int)(sum_ / (float)count_);
              char *buf = new char(16);
              snprintf(buf, sizeof(buf), "%04d-%02d-%02d", val/10000, (val%10000)/100, val%100);
              return TupleCell(field_.attr_type(), buf);
            } break;
          default: {
            LOG_WARN("unsupported attr type: %d", attr_type);
          } break;
        }
      } break;
      case SUM: {
        char *c = strdup(double2string(sum_).c_str());
        return TupleCell(field_.attr_type(), c);
      } break;
      default:
        LOG_ERROR("Unknown aggregate type");
        break;
    }
  }

public:
  AggrType aggr_type_;
  const char *attr_name_ = nullptr;
  Field field_;

  bool flag_; // 标识是否是第一次do_record
  TupleCell value_;
  float sum_;
  int count_;
};